import axios from 'axios'
import router from '../router'
import { Toast } from 'vant'

const Tip = msg => {
  Toast(msg)
}


// export default serve
import qs from 'querystring';

// 创建axios实例
// 创建请求时可以用的配置选项
var instance = axios.create({ timeout: 3000 });
// axios的全局配置
instance.defaults.headers.post['Content-Type'] = 'application/json; charset=UTF-8';
instance.defaults.headers.put['Content-Type'] = 'application/json; charset=UTF-8';
instance.defaults.headers.patch['Content-Type'] = 'application/json; charset=UTF-8';

// 添加请求拦截器(post只能接受字符串类型数据)
instance.interceptors.request.use(function (config) {
    if(localStorage.getItem("token")){
        config.headers.token = `${localStorage.getItem("token")}`
    }
    if (config.method === 'post') {
        config.data =config.data
    }
    return config;
}, function (error) {
    return Promise.reject(error);
});

// 添加响应拦截器
instance.interceptors.response.use(
  res=>{
    if(res.data && res.data.code === 401){
      window.localStorage.removeItem('token')
      router.push({
        name: 'login'
      })
      return Promise.reject(res.data)
    }
    return res.data
  },error=>{
    const { response } = error;
    if (response) {
        errorHandle(response.status, response.data);
        return Promise.reject(response);
    } else {
      console.log('请求失败')
    }
  }
);
const errorHandle = (status, other) => {
    switch (status) {
        case 400:
            Tip(other.message)
            console.log("信息校验失败");
            break;
        case 401:
            Tip(other.message)
            console.log("认证失败");
            break;
        case 403:
            Tip(other.message)
            console.log("token校验失败");
            break;
        case 404:
            Tip(other.message)
            console.log("请求的资源不存在");
            break;
        case 409:
            Tip(other.message)
            console.log("信息校验失败");
            break;
        case 500:
            Tip(other.message)
            break;
        default:
            Tip(other.message)
            break;

    }
}
export default instance;
